import { Sequelize } from 'sequelize'
import config from './index.js'

const env = process.env.NODE_ENV || 'development'
const dbConfig = config.database[env]

// 创建Sequelize实例
const sequelize = new Sequelize(
  dbConfig.database,
  dbConfig.username,
  dbConfig.password,
  {
    host: dbConfig.host,
    port: dbConfig.port,
    dialect: dbConfig.dialect,
    timezone: dbConfig.timezone,
    logging: dbConfig.logging,
    pool: {
      max: 10,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
    define: {
      timestamps: true,
      underscored: true,
      freezeTableName: true,
    },
  },
)

// 测试数据库连接
export async function connectDB() {
  try {
    await sequelize.authenticate()
    console.log('✅ Database connection established successfully.')

    // 在开发环境下同步数据库
    if (env === 'development') {
      // await sequelize.sync({ alter: true })
      console.log('📊 Database synchronized successfully.')
    }
  }
  catch (error) {
    console.error('❌ Unable to connect to the database:', error)
    throw error
  }
}

export { sequelize }
export default sequelize
